package me.liuhui.mall.manager.service.security;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.NoArgsConstructor;
import me.liuhui.mall.repository.model.Admin;
import me.liuhui.mall.repository.model.Permission;
import me.liuhui.mall.repository.model.Role;
import me.liuhui.mall.repository.model.enums.AdminStatus;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author liuhui
 */
@Data
@NoArgsConstructor
public class CurrentAdmin implements UserDetails {

    private Long adminId;
    private String username;
    private String realName;
    private String password;
    private Integer status;
    private Collection<Permission> permissions;

    private Collection<Role> roles;


    public CurrentAdmin(Admin admin) {
        this.setAdminId(admin.getId());
        this.setUsername(admin.getUsername());
        this.setPassword(admin.getPassword());
        this.setRealName(admin.getRealName());
        this.setStatus(admin.getStatus());
    }

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<SimpleGrantedAuthority> result = new HashSet<>();
        if (CollectionUtils.isNotEmpty(permissions)) {
            result.addAll(permissions.stream().map(permission -> new SimpleGrantedAuthority(permission.getCode())).collect(Collectors.toSet()));
        }
        if (CollectionUtils.isNotEmpty(roles)) {
            result.addAll(roles.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role.getCode())).collect(Collectors.toSet()));
        }
        return result;
    }


    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return AdminStatus.NORMAL.getCode().equals(status);
    }
}
